<template>
  <el-container style="flex-direction: column;">
    <!-- 引入顶部导航栏 -->
    <OwnerHeader :userInfo="userInfo" />

    <!-- 第一个区域：操作栏 -->
    <div class="section operation-section">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-input v-model="searchName" placeholder="请输入访客姓名" clearable style="width: 200px;" />
        </el-col>
        <el-col :span="6">
          <el-select v-model="searchState" placeholder="选择状态" clearable>
            <el-option label="申请中" value=1 />
            <el-option label="未到访" value=2 />
            <el-option label="已到访" value=3 />
            <el-option label="拒绝到访" value=4 />
            <el-option label="申请过期" value=5 />
          </el-select>
        </el-col>
        <el-col :span="6">
          <div style="display: flex; align-items: center;">
            <el-date-picker v-model="startTime" type="datetime" placeholder="开始时间" clearable style="margin-right: 10px;"
              value-format="yyyy-MM-dd hh:mm:ss" />
            <span style="margin:10px; color: dimgray;">至</span>
            <el-date-picker v-model="endTime" type="datetime" placeholder="结束时间" clearable
              value-format="yyyy-MM-dd hh:mm:ss" />
          </div>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" size="medium" @click="handleSearch">查询</el-button>
          <el-button type="danger" size="medium" @click="handleBatchDelete">批量删除</el-button>
          <el-button type="success" size="medium" @click="handleAddVisitorClick">添加预约</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 第二个区域：统计区域 -->
    <div class="section stats-section">
      <h2>统&nbsp;&nbsp;&nbsp;&nbsp;计</h2>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-card class="stats-card status-pending">
            <div class="stats-item">
              <div class="stats-label">申请中</div>
              <div class="stats-value">{{ states.pending }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stats-card status-not-arrived">
            <div class="stats-item">
              <div class="stats-label">未到访</div>
              <div class="stats-value">{{ states.notArrived }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stats-card status-arrived">
            <div class="stats-item">
              <div class="stats-label">已到访</div>
              <div class="stats-value">{{ states.arrived }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stats-card status-rejected">
            <div class="stats-item">
              <div class="stats-label">拒绝到访</div>
              <div class="stats-value">{{ states.rejected }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="5">
          <el-card class="stats-card status-expired">
            <div class="stats-item">
              <div class="stats-label">申请过期</div>
              <div class="stats-value">{{ states.expired }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 第三个区域：历史记录区域 -->
    <div class="section history-section">
      <h2>历史记录</h2>
      <el-row :gutter="20">
        <el-col v-for="apply in applyData" :key="apply.id" :span="6">
          <el-card class="visitor-card" :style="{ backgroundColor: statusColors[apply.state] }">
            <div class="card-content">
              <div class="card-info">
                <div class="visitor-name">访客： {{ apply.visitorName }}</div>
                <div class="visitor-time">到访时间：{{ apply.arriveTime }} 到 {{ apply.leaveTime }}</div>
                <div class="visitor-toDo">事由： {{ apply.toDo }}</div>
                <div class="visitor-toDo">目的地： {{ apply.destination }}</div>
                <div class="visitor-toDo">邀请码： {{ apply.invitationCode }}</div>
                <div class="visitor-status">
                  状态:
                  <span v-if="apply.state === 1">申请中</span>
                  <span v-else-if="apply.state === 2">未到访</span>
                  <span v-else-if="apply.state === 3">已到访</span>
                  <span v-else-if="apply.state === 4">拒绝到访</span>
                  <span v-else-if="apply.state === 5">申请过期</span>
                  <span v-else>未知状态</span>
                </div>
              </div>
              <div class="card-actions">
                <el-checkbox v-model="selectedApply[apply.id]" style="margin-right: 10px;" />
                <el-button type="text" @click="handleEditApply(apply)" style="color: blue; font-size: large;">编
                  辑</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 添加访客弹窗 -->
    <el-dialog title="添加访客" :visible.sync="addDialogVisible" width="30%">
      <el-form :model="addForm" label-width="100px">
        <el-form-item label="访客姓名">
          <el-input v-model="addForm.visitorName"></el-input>
        </el-form-item>
        <el-form-item label="访客邮箱">
          <el-input v-model="addForm.visitorEmail"></el-input>
        </el-form-item>
        <el-form-item label="访客手机号">
          <el-input v-model="addForm.visitorPhone"></el-input>
        </el-form-item>
        <el-form-item label="到访地点">
          <el-input v-model="addForm.destination"></el-input>
        </el-form-item>
        <!-- 访客照片 -->
        <el-form-item label="访客照片">
          <el-upload style="text-align:left" ref="pictureUpload" action="#" :list-type="'picture-card'"
            :auto-upload="false" :on-change="handleChange">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
              <span class="el-upload-list__item-actions">
                <!-- 放大查看缩略图 -->
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <!-- 删除缩略图 -->
                <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisiblePicture" :modal="false">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="到访时间范围">
          <el-date-picker v-model="addForm.timeRange" type="datetimerange" range-separator="至" start-placeholder="到访时间"
            end-placeholder="离开时间" value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="事由">
          <el-input v-model="addForm.toDo" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddApply">确定</el-button>
      </span>
    </el-dialog>

    <!-- 修改访客信息弹窗 -->
    <el-dialog title="修改访客信息" :visible.sync="isEditDialogVisible" width="30%">
      <el-form :model="currentApply" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="currentApply.visitorName" :disabled="true" />
        </el-form-item>
        <el-form-item label="邀请码">
          <el-input v-model="currentApply.invitationCode" :disabled="true" />
        </el-form-item>
        <el-form-item label="目的地">
          <el-input v-model="currentApply.destination" />
        </el-form-item>
        <el-form-item label="事由">
          <el-input v-model="currentApply.toDo" />
        </el-form-item>
        <!-- 访客照片 -->
        <el-form-item label="访客照片">
          <el-upload style="text-align:left" ref="pictureUpload" action="#" :list-type="'picture-card'"
            :auto-upload="false" :on-change="handleChange" :file-list="initialFileList">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
              <span class="el-upload-list__item-actions">
                <!-- 放大查看缩略图 -->
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <!-- 删除缩略图 -->
                <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisiblePicture" :modal="false">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="到访时间">
          <el-date-picker v-model="currentApply.arriveTime" type="datetime" placeholder="选择时间"
            value-format="yyyy-MM-dd HH:mm:ss" />
        </el-form-item>
        <el-form-item label="离开时间">
          <el-date-picker v-model="currentApply.leaveTime" type="datetime" placeholder="选择时间"
            value-format="yyyy-MM-dd HH:mm:ss" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdateVisitor">保存</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
import OwnerHeader from '@/components/owner_components/OwnerHeader.vue';
import { parseJwt } from '@/utils/parseJWT';
import service from '@/utils/request';

export default {
  name: 'OwnerVisitorView',
  components: {
    OwnerHeader,
  },
  data() {
    return {
      userInfo: {},

      searchName: '', // 访客姓名查询条件
      searchState: '', // 状态筛选条件
      startTime: '', // 开始时间
      endTime: '', // 结束时间
      selectedApply: {}, // 选中的访客ID，键为ID，值为是否选中
      applyData: [],
      isEditDialogVisible: false, // 编辑弹窗是否显示
      currentApply: {}, // 当前编辑的访客信息

      states: {
        pending: 0,
        notArrived: 0,
        arrived: 0,
        rejected: 0,
        expired: 0,
      },

      // 状态对应的背景颜色
      statusColors: {
        1: '#E6A23C', // 申请中：蓝色
        2: '#067affa6',   // 未到访：橙色
        3: '#67C23A',   // 已到访：绿色
        4: '#f99090',   // 拒绝到访：红色
        5: '#999999'    // 申请过期：灰色
      },

      //图片上传缩略图所需的属性
      dialogImageUrl: '',
      dialogVisiblePicture: false,
      disabled: false,
      //  图片上传文件列表
      pictureFile: {},
      initialFileList: [],
      updateImage: false,

      addDialogVisible: false, // 控制添加访客弹窗的显示
      addForm: { // 添加访客的表单数据
        visitorName: '',
        visitorEmail: '',
        visitorPhone: '',
        visitorImage: '',
        destination: '',
        timeRange: [],
        toDo: '',
        state: 2 // 默认状态为待审核
      },
    };
  },
  mounted() {
    this.userInfo = parseJwt(localStorage.getItem('token')).payload;
    this.getApplyData();
  },
  methods: {
    getApplyData() {
      service.get('/api/user/apply/getApplyData', {
        params: {
          userId: this.userInfo.id,
          visitorName: this.searchName,
          state: this.searchState,
          startTime: this.startTime,
          endTime: this.endTime,
        }
      })
        .then(result => {
          this.states.arrived = 0;
          this.states.pending = 0;
          this.states.notArrived = 0;
          this.states.rejected = 0;
          this.states.expired = 0;

          result = result.data;
          console.log('登录成功,申请信息:', result.data);
          if (result.code == 1) {
            this.applyData = result.data;
            console.log('登录成功,this.applyData信息:', this.applyData);
            this.applyData.forEach(item => {
              if (item.state === 1) {
                this.states.pending++;
              } else if (item.state === 2) {
                this.states.notArrived++;
              } else if (item.state === 3) {
                this.states.arrived++;
              } else if (item.state === 4) {
                this.states.rejected++;
              } else if (item.state === 5) {
                this.states.expired++;
              }
            });
          }
        });
    },

    handleSearch() {
      this.getApplyData();
    },

    // 批量删除
    handleBatchDelete() {
      // 获取值为 true 的键
      const trueKeys = Object.keys(this.selectedApply).filter(key => this.selectedApply[key] === true);
      // 将 trueKeys 数组中的元素转换为 Number 类型
      const ids = trueKeys.map(key => parseInt(key, 10));
      console.log('批量删除的ID：', ids);
      if (ids.length === 0) {
        this.$message.warning('请选择要删除的访客');
        return;
      }

      service.post('/api/user/apply/deleteApply', ids)
        .then((result) => {
          result = result.data;
          if (result.code == 1) {
            this.$message.success('批量删除成功');
            this.getApplyData(); // 刷新数据
          } else {
            this.$message.success(result.msg);
          }

        })
        .catch((error) => {
          this.$message.error('删除访客失败');
          console.error(error);
        });
      this.getApplyData();
    },

    /**
      * 打开添加访客弹窗
      */
    handleAddVisitorClick() {
      this.addDialogVisible = true; // 打开弹窗
    },
    handleAddApply() {
      let newData = {
        userId: this.userInfo.id,
        arriveTime: this.addForm.timeRange[0],
        leaveTime: this.addForm.timeRange[1],
        visitorName: this.addForm.visitorName,
        visitorEmail: this.addForm.visitorEmail,
        visitorPhone: this.addForm.visitorPhone,
        destination: this.addForm.destination,
        toDo: this.addForm.toDo,
        state: 2,
        visitorImage: '',
      }
      const fromData = new FormData();
      fromData.append('image', this.pictureFile.raw);
      service.post('/api/upload/aliyun', fromData)
        .then(result => {
          result = result.data;
          console.log('上传成功', result);
          if (result.code == 1) {
            newData.visitorImage = result.data;

            console.log("---------------");
            console.log(newData);
            console.log(newData.visitorImage);
            // 提交添加访客申请
            service.post('/api/user/apply/addApply', newData)
              .then(result => {
                result = result.data;
                if (result.code === 1) {
                  this.$message.success('添加访客成功');
                  this.addDialogVisible = false; // 关闭弹窗
                  this.getApplyData(); // 刷新数据
                } else {
                  this.$message.error(result.msg);
                }
              })
              .catch(error => {
                this.$message.error('添加访客失败');
                console.error(error);
              });
          } else {
            alert(result.msg);
          }
        })
    },
    // 图片缩略图放大查看
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisiblePicture = true;
    },

    //图片缩略图组件选择图片后事件
    handleChange(file, fileList) {
      console.log(file, fileList);
      if (fileList.length > 1) {
        this.$message({ type: 'error', message: '只能上传一张图片' });
        this.handleRemove(file);
        console.log(file, fileList);
        return;
      }
      this.pictureFile = file;
    },
    //图片缩略图删除
    handleRemove(file) {
      console.log(file);
      let uploadFiles = this.$refs.pictureUpload.uploadFiles
      for (var i = 0; i < uploadFiles.length; i++) {
        if (uploadFiles[i]['uid'] == file.uid) {
          uploadFiles.splice(i, 1)
        }
      }
      this.updateImage = true;
    },

    // 打开编辑弹窗
    handleEditApply(apply) {
      this.currentApply = { ...apply };
      console.log(this.currentApply);
      this.isEditDialogVisible = true;
      this.initialFileList = [];
      this.initialFileList.push({ url: apply.visitorImage });
      this.updateImage = false;
    },

    // 保存修改的访客信息
    handleUpdateVisitor() {
      if (this.updateImage) {
        const fromData = new FormData();
        fromData.append('image', this.pictureFile.raw);
        service.post('/api//upload/aliyun', fromData)
          .then(result => {
            result = result.data;
            console.log('上传成功', result);
            if (result.code == 1) {
              this.currentApply.visitorImage = result.data;
              // 提交添加访客申请
              service.post('/api/user/apply/updateApply', this.currentApply)
                .then(result => {
                  result = result.data;
                  if (result.code === 1) {
                    this.$message.success('访客信息修改成功');
                    this.isEditDialogVisible = false;
                    this.getApplyData(); // 刷新数据
                  } else {
                    this.$message.error(result.msg);
                  }
                })
                .catch(error => {
                  this.$message.error('添加访客失败');
                  console.error(error);
                });
            } else {
              alert(result.msg);
            }
          })
      } else {
        service.post('/api/user/apply/updateApply', this.currentApply)
          .then(result => {
            result = result.data;
            if (result.code === 1) {
              this.$message.success('访客信息修改成功');
              this.isEditDialogVisible = false;
              this.getApplyData(); // 刷新数据
            } else {
              this.$message.error(result.msg);
            }
          })
          .catch(error => {
            this.$message.error('添加访客失败');
            console.error(error);
          });
      }
    },
  },
};
</script>

<style scoped>
.section {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.operation-section {
  background-color: #f5f7fa;
}

.stats-section .stats-card {
  margin-bottom: 10px;
  padding: 15px;
}

.stats-section .stats-item {
  text-align: center;
}

.stats-section .stats-label {
  font-size: 14px;
  color: #666;
}

.stats-section .stats-value {
  font-size: 24px;
  font-weight: bold;
  color: #545454;
}

.history-section .visitor-card {
  margin-bottom: 10px;
  padding: 15px;
  color: #fff;
  /* 设置文字颜色为白色，确保可读性 */
  min-height: 200px;
  /* 设置卡片最小高度，确保高度一致 */
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  /* 内容在垂直方向上均匀分布 */
}

.card-content {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
  /* 使内容占满整个卡片 */
}

.card-info {
  flex: 1;
  /* 信息部分占满剩余空间 */
}

.card-actions {
  display: flex;
  align-items: center;
  /* 操作按钮垂直居中 */
  justify-content: flex-end;
  /* 操作按钮靠右对齐 */
}

.visitor-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  /* 调整标题与内容的间距 */
}

.visitor-time {
  color: #eee;
  /* 浅色文字，确保在深色背景上可读 */
  margin: 5px 0;
}

.visitor-toDo {
  color: #eee;
  /* 浅色文字，确保在深色背景上可读 */
  margin: 5px 0;
}

.visitor-status {
  color: #eee;
  /* 浅色文字，确保在深色背景上可读 */
  font-size: 14px;
}

.status-pending {
  background-color: #E6A23C;
  /* 申请中：橙色 */
}

.status-not-arrived {
  background-color: #067affa6;

  /* 申请过期：蓝色 */
}

.status-arrived {
  background-color: #67C23A;
  /* 已到访：绿色 */
}

.status-rejected {
  background-color: #f99090;
  /* 拒绝到访：红色 */
}

.status-expired {
  background-color: #999999;
  /* 未到访：灰色 */
}

/* 修改上传图片组件框大小 */
::v-deep .el-upload--picture-card {
  width: 100px;
  height: 100px;
}

::v-deep .el-upload {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

::v-deep .el-upload-list--picture-card .el-upload-list__item {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

::v-deep .el-upload-list--picture-card .el-upload-list__item-thumbnail {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
</style>